package subumbo.audio.generator
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;

	public class SoundLoader
	{
		protected const _sound:Sound = new Sound();
		protected var _loaded:Boolean;
		protected var _progressFunction:Function;
		
		public function SoundLoader()
		{
			// CONSTRUCTOR
		}
		
		public function load(url:String):void
		{
			registerListener();
			_sound.load(new URLRequest(url));
		}

		
		protected function loadComplete( event: Event ): void
		{
			unregisterListener();
			_loaded = true;
		}
		
		protected function loadError( event: IOErrorEvent ): void
		{
			unregisterListener();
			Alert.show("Sound load failed: " +  event.text );
		}

		protected function registerListener(): void
		{
			_sound.addEventListener( Event.COMPLETE, loadComplete );
			_sound.addEventListener( IOErrorEvent.IO_ERROR, loadError );
			_sound.addEventListener( ProgressEvent.PROGRESS, onProgress);
		}
		
		protected function onProgress(e:ProgressEvent):void
		{
			if(_progressFunction)_progressFunction.call();
			else trace("SoundLoader::onProgress() \n set progressFunction")
		}

		protected function unregisterListener(): void
		{
			_sound.removeEventListener( Event.COMPLETE, loadComplete );
			_sound.removeEventListener( IOErrorEvent.IO_ERROR, loadError );
			_sound.removeEventListener( ProgressEvent.PROGRESS, onProgress);
		}
		
		public function set progressFunction(val:Function):void
		{
			_progressFunction = val;
		}
	}
}